"""
from contextlib import contextmanager

@contextmanager
def my_open(file_name, mode):
    try:
        f = open(file_name, mode)
        print("上文管理器：打开文件")
        yield f
    except Exception as e:
        f.close()
        print("下文管理器：关闭文件")
        raise e


with my_open("2.txt", "w") as f:
    data = f.read()
    print(data)

# with open("2.txt", "r") as f:
#     data = f.read()
#     print(data)

"""

class my_open(object):

    def __init__(self, file_name, mode):
        self.__file_name = file_name
        self.__file_mode = mode

    def __enter__(self):
        print("上文管理器：打开文件")
        self.__file = open(self.__file_name, self.__file_mode)
        return self.__file

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("下文管理器：关闭文件")
        self.__file.close()


with my_open("3.txt", "r") as f:
    data = f.read()
    print(data)
